<?php
header("Cache-Control: no-store, no-cache, must-revalidate");

class mysqlphpgrid {
	var $add_allowed 	= false;	// may the user add records?
	var $delete_allowed 	= true;		// may the user delete records?
	var $update_allowed 	= true;		// may the user update individual fields of records?
	var $pagelength		= 20;		// length of the grid. If longer it will do pagination
	var $show_id_field	= false;	// to show the id field or not
	var $where			= 1;		// where clause
	var $section			= "mysqlphpgrid.section.php";	// section that will be loaded when a link where pressed
	var $server, $user, $pw, $db, $table;
	var $connection;
	var $orderbystr;
	var $ordstr;
	var $staff;
	var $ord, $desc;
	var $idname = "";
	var $idcolnr;
	function mysqlphpgrid($table, $fields = null) {
//		require_once("../include/webdb.inc");
		$this->server = WEBDB_MYSQL_SRV;
		$this->user = WEBDB_MYSQL_USR;
		$this->pw = WEBDB_MYSQL_PWD;
		$this->db = WEBDB_MYSQL_NDB;
		$this->table = $table;
		$this->add_allowed = true;
		//$this->where = $where;
		$this->conn = mysql_connect(WEBDB_MYSQL_SRV, WEBDB_MYSQL_USR, WEBDB_MYSQL_PWD) or die(mysql_error());
		mysql_select_db(WEBDB_MYSQL_NDB) or die (mysql_error());
		$this->fields = $fields;
		//$this->section = $section;
		//if($qs->row['privs'] > 2)
//		$qs = new cWebDBq($db, "staff");
//		if(!$session->GetValue("staff") || !$qs->Seek("*", "id=".$session->GetValue("staff"))) echo "tronco";
		// Initialize the name of the id field:
		if($this->fields!=null) {
			$tmpFields = implode(', ', array_keys($fields));
			$result = mysql_query("SELECT $tmpFields FROM $this->table WHERE $this->where LIMIT 1", $this->conn);
		} else {
			$result = mysql_query("SELECT * FROM $this->table WHERE $this->where LIMIT 1", $this->conn);
		}
//		 Check for a primary key
				for($i=0; $i < mysql_num_fields($result); $i++)  {
					$fld = mysql_fetch_field($result, $i);
					if ($fld->primary_key == 1) {
						$this->idname = $fld->name;
						$this->idcolnr = $i;
					}
					elseif ($fld->unique_key == 1) {
						$this->idname = $fld->name;
						$this->idcolnr = $i;
					}
				}
				if ($this->idname == "") die("Could not find primary or unique key");
				mysql_free_result($result);
	}
	function __destruct() {
		@mysql_close($this->conn);
	}
	function UpdateData() {
		$bool = $this->update_data();
		if ($_REQUEST["a"]) exit($bool);	//Ajax, return true/false
		$this->do_orderby();
	}
	function ShowTable($idSession = null, $privs = null){
		$str = "";
		?>
		<script type="text/javascript" src="js/mootools.js"></script>
		<script type="text/javascript">
		var ajaxongoing = false;
		var type = "";
		function td_change(obj) {
			var url = '<?echo $this->section."?staff=".$this->staff."&id=".$_REQUEST['id'];?>&a=1&op=u&oid='+input_obj.id+'&value='+obj.value+'&idSession=<?echo $idSession;?>&privs=<?echo $privs;?>';
			myajax = new Ajax(url, {
				method: 'get',
				onComplete: function(){
					if(this.transport.responseText[0]=='0')
						remove_form(null);
					else
						remove_form(obj.value);
					ajaxongoing = false;
				}
			}).request();
			ajaxongoing = true;
		}
		var input_obj;
		var input_obj_old_innerHTML;
		var input_obj_old_onclick;
		function keyPressed(obj, e) {
			if(window.event)	k = e.keyCode 	// IE
			else				k = e.which 					// Netscape/Firefox/Opera
			if(k==27) remove_form(null); 			//escape key; doesn't work in IE
			if(k==39) alert(obj['id']);	 			//escape key; doesn't work in IE
		}
		function remove_form(str){
			if (input_obj) {
					input_obj.innerHTML = (str) ? str : input_obj_old_innerHTML;
					if (str) input_obj_old_innerHTML = str;
				if (str) new Fx.Color(input_obj.id, 'color', {duration: 4000}).fromColor('F00');
				input_obj.onclick = input_obj_old_onclick;
			}
		}
		function blur(obj) {
			var url = '<?echo $this->section."?staff=".$this->staff."&id=".$_REQUEST['id'];?>&a=1&op=u&oid='+input_obj.id+'&value='+obj.value+'&idSession=<?echo $idSession;?>&privs=<?echo $privs;?>';
			myajax = new Ajax(url, {
				method: 'get',
				onComplete: function(){
					if(this.transport.responseText[0]=='0')
						remove_form(null);
					else
						remove_form(obj.value);
					ajaxongoing = false;
				}
			}).request();
			ajaxongoing = true;
		}
		function create_form(obj){
			if (ajaxongoing) return;
			remove_form(null);
			input_obj = obj;
			input_obj_old_innerHTML = obj.innerHTML;
			input_obj_old_onclick 	= obj.onclick;
			formid = obj.id + "|1"; // to prevent two objects from having the same id
			fldcode = obj.id.slice(obj.id.indexOf("|")+1);
			fldtype = get_fldtype(fldcode);
			obj.innerHTML = "<textarea id=\"" + formid + "\" cols=46 rows=" + Math.ceil(obj.innerHTML.length/46) + " onBlur=\"td_change(this)\">" + obj.innerHTML + "</textarea>";
			obj.onclick = null;
			document.getElementById(formid).focus();
		}
		function tr_del(obj, s, ord) {
			if (window.confirm('Realmente quieres borrar el comentario?')) {
				ajaxRequest('<?echo $this->section."?staff=".$this->staff."&id=".$_REQUEST['id'];?>&op=d&oid='+obj.id+'&ord='+ord+'&s='+s+'&idSession=<?echo $idSession;?>&privs=<?echo $privs;?>');
			}
			new Fx.Color('row'+obj.id, 'color', {duration: 3000}).toColor('#000000');
		}
		function tr_add(obj) {
			url = '<?echo $this->section . "?staff=" . $this->staff . "&id=" . $_REQUEST['id']; ?>&op=a&oid=<? echo $_REQUEST['oid']; ?>&idSession=<?echo $idSession;?>&privs=<?echo $privs;?>&idns=' + new Date().getTime();
			new Ajax(url, {method: 'GET', update: 'grid'}).request();return false;
		}
		function td_sort_desc(obj){
			ajaxRequest('<?echo $this->section."?staff=".$this->staff."&id=".$_REQUEST['id'];?>&ord='+obj.id+',d&idSession=<?echo $idSession;?>&privs=<?echo $privs;?>');
		}
		function td_sort(obj){
			ajaxRequest('<?echo $this->section."?staff=".$this->staff."&id=".$_REQUEST['id'];?>&ord='+obj.id+'&idSession=<?echo $idSession;?>&privs=<?echo $privs;?>');
		}
		</script>
		<?
		$result = $this->select();
		//Header:
		$str .= "\n<table class=\"mysqlphpgrid\">\n<tr>\n";
		if ($this->delete_allowed) $str .= "<th></th>\n";
		$tmpFields = array_values($this->fields);
		$tmpLabels = array_keys($this->fields);
		for($i=0; $i < count($this->fields); $i++)  {
			$fldname = $tmpFields[$i];
			$fldlabel = $tmpLabels[$i];
			$oid = $fldlabel . ((($this->ord == $fldlabel) && (!$this->desc))? ",d" : "");
			$gripid = $oid . "grip";
			$imgsrc = (($this->ord != $fldlabel)? "sortno.gif" : (($this->desc)? "sort2.gif" : "sort1.gif"));
			if ($fldname != 'id'){
				$str .= "<th class=\"th\" nowrap onclick=\"td_sort(this)\" title=\"Click para ordenar\" id=\"" . $oid . "\">";
				$str .= $fldname;
				$str .= "<img src=\"img/" . $imgsrc . "\">";
				$str .= "</th>\n";
			}
		}
		$str .= "</tr>\n";
		//write javascript function for getting field types:
		$colresult = mysql_query("SHOW COLUMNS FROM " . $this->table . " FROM " . $this->db, $this->conn) or die(mysql_error());
		$str .= "<script>function get_fldtype(fldname){\n";
		for($i=0; $i < mysql_num_rows($colresult); $i++)  {
			list($fldname, $fldtype, $fldnull, $fldkey, $flddefault, $fldextra) = mysql_fetch_row($colresult);
			$str .= "if (fldname == \"$fldname\") return(\"$fldtype\");\n";
		}
		$str .= "return(\"\");}</script>\n";
		mysql_free_result($colresult);
		//Rows:
		$c = 0;
		$ord = $_REQUEST["ord"];
		if ($ord == "") $ord = "id";
			$s = $_REQUEST["s"];

		if ($s == "") $s = 0;
		if ($s < 0) $s = floor(mysql_num_rows($result)/$this->pagelength);

		for (($i=$s*$this->pagelength) && mysql_data_seek($result, $i); $i < min(mysql_num_rows($result), ($s+1)*$this->pagelength) ; $i++)  {
			$row = mysql_fetch_array($result);
			$oid = mysql_result($result, $i);
			$str .= "<tr id=\"row" . $oid . "\">\n";
			if ($c++ % 2 == 0) 	$class = "tdeven";
			else	$class = "tdodd";

			if ($this->delete_allowed) $str .= "<td class=\"tddel\" >" .
			"<img src=\"img/del.gif\" onclick=\"tr_del(this, $s, '$ord')\"" . " id=\"" . $oid . "\"" .
			"onmouseover=\"this.src='img/del2.gif'\" onmouseout=\"this.src='img/del.gif'\" title=\"Eliminar este comentario\"/>" .
			"</td>\n";
			for($j=0; $j < mysql_num_fields($result); $j++)  {
				//					$fldname = mysql_fetch_field($result, $j)->name;
				$fldname = mysql_field_name($result, $j);
				if (($fldname == $this->idname) && ($this->show_id_field == false)) continue;
				$data = trim($row[$j]);
				switch ($fldname) {
					case 'text':
						if(isset($_REQUEST['idSession'])) {
							if ($_REQUEST['privs'] == 0 || $_REQUEST['idSession'] == $row['staff_id']) {
								$str .= "<td class=\"$class\" onclick=\"create_form(this)\" "."id=\"" . $oid .	"|" . $fldname . "\" onblur=\"blur(this)\">".$data."</td>\n";
							} else {
								$str .= "<td class=\"$class\" id=\"" . $oid .	"|" . $fldname . "\">".$data."</td>\n";
							}
							} else {
							if ($privs == 0 || $idSession == $row['staff_id']) $str .= "<td class=\"$class\" onclick=\"create_form(this)\" "." id=\"" . $oid .	"|" . $fldname . "\" onblur=\"blur(this)\">".$data."</td>\n";
							else $str .= "<td class=\"$class\" id=\"" . $oid .	"|" . $fldname . "\">".$data."</td>\n";
						}
						break;
					case 'date':
						setlocale(LC_ALL, "sp");
						$str .= "<span class=\"fecha\">" .strftime("%d-%m-%Y %R", strtotime($data)) . "</span></td>\n";
						break;
					case 'staff_id':
						$resultStaff=mysql_query("SELECT cid FROM staff WHERE id=$data", $this->conn);
						$nameStaff=mysql_fetch_assoc($resultStaff);
						$str .= "<td class=\"$class\" colspan=2><strong>" . $nameStaff['cid'] . "</strong><br>\n";
						break;
					case 'id':
						break;
				}
			}
			$str .= "</tr>\n";
		}
		//An extra row for adding records:
		if ($this->add_allowed) {
			$str .= "<tr>\n";
			$str .= "<td>" .
			"<img src=\"img/add.gif\" onclick=\"tr_add(this)\"" .
			"onmouseover=\"this.src='img/add2.gif'\" onmouseout=\"this.src='img/add.gif'\"" .
			"title=\"Insertar nuevo comentario\"/>" .
			"</td>\n";
			$str .= "<td colspan='" . mysql_num_fields($result) . "'></td>\n";
			$str .= "</tr>\n";
		}
		// Page pointers:
		if (mysql_num_rows($result) > $this->pagelength) {
			$str .= "<tr><td class=\"tdpp\" colspan='" . (mysql_num_fields($result)+1) . "' align='center'>\n";
			if ($s > 0) {
				$url = "$this->section?staff=".$this->staff."&id=".$_REQUEST['id']."&s=" . ($s-1) . "&ord=" . $this->ordstr;
				$str .= "<a href=\"#\" onclick=\"javascript:ajaxRequest('$url');\">" . "<" . "</a>\n";
			} else
			$str .= "&nbsp;&nbsp;";
			for ($j=0; ($j*$this->pagelength) < mysql_num_rows($result); $j++) {
				if ($j == $s)
				$str .= ($j+1) . "&nbsp";
				else {
					$url = "$this->section?staff=".$this->staff."&id=".$_REQUEST['id']."&s=" . ($j) . "&ord=" . $this->ordstr;
					$str .= "<a href=\"#\" onclick=\"javascript:ajaxRequest('$url');\">" . ($j+1) . "</a>\n";
				}
			}
			if ($s < $j-1) {
				$url = "$this->section?staff=".$this->staff."&id=".$_REQUEST['id']."&s=" . ($s+1) . "&ord=" . $this->ordstr;
				$str .= "<a href=\"#\" onclick=\"javascript:ajaxRequest('$url');\">" . ">" . "</a>\n";
			}
			$str .= "</td></tr>\n";
		}
		//Close Table
		$str .=  "</table>\n";
		mysql_free_result($result);
		return $str;
	}
	// Effectuate changes in database
	function update_data(){
		$op = $_REQUEST["op"];
		$oid = $_REQUEST["oid"];
		$value = $_REQUEST["value"];
		list ($id1, $fld) = split('[|]', $oid);
		$id1 = mysql_real_escape_string($id1);
		$fld = mysql_real_escape_string($fld);
		switch ($op) {
			case ("a") : return($this->add($oid));
			case ("d") : if ($this->delete_allowed) return($this->delete($id1)); else return(false);
			case ("u") : if ($this->update_allowed) return($this->update($id1, $fld, $value)); else return(false);
			case ("ae") : return($this->addForm()); //add data from a form
		}
		return(false);
	}
	function select(){
		if($this->fields != null) {
			$tmpFields = implode(', ', array_keys($this->fields));
			$res = mysql_query("SELECT $tmpFields FROM $this->table WHERE $this->where" . $this->orderbystr, $this->conn) or die(mysql_error());
		}
		else {
			$res = mysql_query("SELECT * FROM $this->table WHERE $this->where" . $this->orderbystr, $this->conn) or die(mysql_error());
		}
		return ($res);
	}
	function add($sid){
		$sql = sprintf("INSERT INTO %s (sid, staff_id, date) VALUES(%d, %d, now())", $this->table, $_REQUEST['id'], $this->staff);
		mysql_query($sql, $this->conn) or die(mysql_error());
		if (mysql_affected_rows($this->conn) == 1) return(true); else return(false);
	}
	function exists($oid, $fld = "") {
		$res = $this -> select();
		// check field
		if ($fld != "") {
			$found = false;
			while (($field = mysql_fetch_field($res)) != null) {
				if ($field->name == $fld)
				{
					$found = true;
					break;
				}
			}
			if (!$found) return(false);
		}
		// check id
		for ($i=0; $i < mysql_num_rows($res); $i++)  {
			$row = mysql_fetch_array($res);
			if ($row[$this->idcolnr] == $oid) return(true);
		}
		return(false);
	}
	function addForm() {
		if (mysql_affected_rows($this->conn) == 1) return(true);
	}
	function delete($oid){
		if (!$this->exists($oid)) return(false);
		mysql_query("DELETE FROM $this->table WHERE $this->idname='$oid'", $this->conn) or die(mysql_error());
		return(true);
	}
	function update($oid, $fld, $value){
		if ($this->exists($oid, $fld)) {
			mysql_query("UPDATE $this->table SET $fld='$value' WHERE $this->idname='$oid'", $this->conn) or die(mysql_error());
			if (mysql_affected_rows($this->conn) == 1) {
				$res = mysql_query("SELECT $fld FROM $this->table WHERE $this->idname='$oid'", $this->conn) or die(mysql_error());
				$row = mysql_fetch_array($res);
				return("1," . $row[0]);
			}
		}
		return("0");
	}
	// Do the sorting
	function do_orderby() {
		if ($_REQUEST["ord"] != "")
			$this->ordstr = mysql_real_escape_string($_REQUEST["ord"]);
		else
			$this->ordstr = $this->idname;
		list ($this->ord, $this->desc) = split('[,]', $this->ordstr);
		if ($this->ord)  $this->orderbystr = " ORDER BY " . $this->ord;
		if ($this->desc) $this->orderbystr .= " DESC";
	}
	function createForm(){
		$form=new form();
		$form->formFromTable();
	}
}
?>